package com.example.chatgpt.service.impl;

import com.example.chatgpt.model.GPTResponse;
import com.example.chatgpt.model.Q_A;
import com.example.chatgpt.service.ChartGPTService;
import com.theokanning.openai.OpenAiService;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.completion.CompletionResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;




@Service
public class ChartGPTServiceImpl implements ChartGPTService {
    @Value("${open.ai.key}")
    private String apiKey;

    @Value("${open.ai.maxTokens}")
    private Integer maxTokens;

    @Value("${open.ai.model}")
    private String model;

    @Value("${open.ai.temperature}")
    private Double temperature;
    @Autowired
    private OpenAiService openAiService;
    @Autowired
    private RedisTemplate redisTemplate;



    @Override
    public Q_A send(String prompt) {
        // 设置代理服务器的主机和端口
        String proxyHost = "127.0.0.1";
        int proxyPort = 7890;
        if (redisTemplate.opsForValue().get("user") == null) {
            redisTemplate.opsForValue().set("user","\nUser: " + prompt );
        }else{
            prompt=redisTemplate.opsForValue().get("user") + "\nUser: " + prompt;
        }


        // 设置代理
        System.setProperty("http.proxyHost", proxyHost);
        System.setProperty("http.proxyPort", Integer.toString(proxyPort));
        System.setProperty("https.proxyHost", proxyHost);
        System.setProperty("https.proxyPort", Integer.toString(proxyPort));
        CompletionRequest completionRequest = CompletionRequest.builder()
                .prompt(prompt)
                .model(model)
                .echo(true)
                .temperature(temperature)
                .topP(1d)
                .frequencyPenalty(0d)
                .presencePenalty(0d)
                .maxTokens(maxTokens)
                .build();
        CompletionResult completionResult = openAiService.createCompletion(completionRequest);
        String generatedReply = completionResult.getChoices().get(0).getText().replaceAll("：",":");
        redisTemplate.opsForValue().append("user", generatedReply);
        GPTResponse response=new GPTResponse();
        Q_A resp = new Q_A();
        resp.setAnswer(generatedReply.substring((generatedReply.lastIndexOf(":") + 1)));
        resp.setQuestion(prompt.substring((prompt.lastIndexOf(":") + 1)));
        return resp;
    }

}
